﻿// Copyright 2008 Rory Plaire (codekaizen@gmail.com)

using System;
using System.IO;
using System.Xml.Linq;

namespace PerformanceDataRecorder
{
    public class Recorder
    {
        private readonly String _fileName;
        private readonly XElement _records;

        public Recorder(String fileName)
        {
            _fileName = fileName;

            if (!File.Exists(fileName))
            {
                using (TextWriter writer = File.CreateText(_fileName))
                {
                    XElement.Parse("<PerformanceData />").Save(writer);
                }
            }

            _records = XElement.Load(fileName);
        }

        public void Log(String technology, Type containerType, Type itemType, Int32 items, TimeSpan duration)
        {
            _records.Add(new XElement("TimeResult",
                new XAttribute("Timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")),
                new XAttribute("Technology", technology),
                new XAttribute("Container", containerType),
                new XAttribute("ItemType", itemType),
                new XAttribute("ItemCount", items), 
                new XAttribute("Duration", duration.TotalMilliseconds.ToString())));

            Save();
        }

        public void Save()
        {
            _records.Save(_fileName);
        }
    }
}
